#pragma once
#include <memory>
#include "objectId.h"
#include <shared_mutex>

namespace jm
{

enum class OpenType : unsigned int
{
	read = 1,
	write = 2,
};

template <typename T>
class my_shared_ptr : std::shared_ptr<T>
{
public:
	my_shared_ptr(std::shared_ptr<T> obj, OpenType type)
		: m_obj(obj), m_type(type) { }
	virtual ~my_shared_ptr() { close(); }

	void close()
	{
		if (!m_closed)
		{
			std::shared_ptr<T> obj;
			if (m_obj.expired())
			{
				obj = m_obj.lock();
			}
			if (obj)
			{
				obj->close(m_type);
			}
			m_closed = true;
		}
	}

	bool isClosed() { return m_closed; }

protected:
	std::weak_ptr<T> m_obj;
	bool m_closed = false;
	OpenType m_type;
};

	class Entity_Export objectBase : public std::enable_shared_from_this<objectBase>
	{
	public:
		objectBase() = default;
		virtual ~objectBase() = default;

		jm::objectId getId() const;
		void setId(const objectId& objId);

		void setDb(objectIdSPtr dbId);
		objectIdSPtr getDb() const;

		bool open(OpenType type);

		virtual void close(OpenType type);

	public:

	protected:

	protected:

		jm::objectId m_objId;
		std::weak_ptr<objectId> m_dbId;

		std::shared_mutex m_s_mutex;
	};
	using objectBasePtr = std::shared_ptr<objectBase>;
	using objectBaseMSPtr = my_shared_ptr<objectBase>;
}